<template>
  <div class="image-list">
    <!--
        如果给按钮注册点击事件的话，会导致每次发送2次请求，
        正确的方式是使用组件提供的change事件
      -->
    <div class="action-head">
      <el-radio-group
        v-model="is_collected"
        size="mini"
        @change="loadImages(1)"
      >
        <el-radio-button :label="false">全部</el-radio-button>
        <el-radio-button :label="true">收藏</el-radio-button>
      </el-radio-group>
      <el-button
        v-if="isShowAdd"
        size="mini"
        type="success"
        @click="dialogUploadVisible=true"
      >上传素材
      </el-button>
    </div>
    <el-row :gutter="10">
      <el-col
        :xs="12"
        :sm="8"
        :md="6"
        :lg="4"
        :xl="2"
        v-for="(img, index) in images"
        :key="index"
        class="image-item"
      >
        <el-image
          style="height: 100px"
          :src="img.url"
          fit="cover"
          @click="selected = index"
        ></el-image>
        <div
          class="selected"
          v-if="isShowSelected && selected === index"
        ></div>
        <div
          v-if="isShowAction"
          class="image-action"
        >
          <!--
            class 样式绑定
            {
              css类名: 绑定值（true作用类名，false不作用类名）
            }
          -->
          <!--<i :class="{-->
          <!--  'el-icon-star-on': img.collect,-->
          <!--  'el-icon-star-off': !img.collect-->
          <!--}"-->
          <!--   @click="onCollect(img)"-->
          <!--/>-->
          <!--<i class="el-icon-delete"/>-->
          <el-button
            :icon="img.is_collected ? 'el-icon-star-on' : 'el-icon-star-off'"
            circle
            size="mini"
            :loading="img.loading"
            @click="onCollect(img)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            :loading="img.loading"
            @click="onDelete(img)"
          />
        </div>
      </el-col>
    </el-row>
    <el-pagination
      layout="prev, pager, next"
      background
      :total="totalCount"
      :page-size="pageSize"
      :current-page="page"
      @current-change="onPageChange"/>

    <!--
      :show-file-list="false"：不展示上传素材对话框中的图片上传历史
      :visible.sync="dialogUploadVisible"：显示或关闭对话框
      :append-to-body="true"：将对话框中的内容显示到body层
    -->
    <el-dialog
      title="上传素材"
      :visible.sync="dialogUploadVisible"
      :append-to-body="true"
    >
      <!--
        upload 组件本身就支持请求提交上传操作
        所以不用自己单独发送上传请求
        请求方法：默认POST
        请求路径：action指定完整的文件上传接口地址
        请求头：headers
      -->
      <el-upload
        class="upload-demo"
        drag
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        multiple
        name="image"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="onUploadSuccess"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { collectImages, deleteImages, getImages } from '@/api/image'

const user = JSON.parse(window.localStorage.getItem('user'))
export default {
  name: 'ImageList',
  components: {},
  props: {
    isShowAdd: {
      type: Boolean,
      default: true
    },
    isShowAction: {
      type: Boolean,
      default: true
    },
    isShowSelected: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      is_collected: false, // 是否收藏
      images: [], // 图片列表
      dialogUploadVisible: false,
      totalCount: 0,
      pageSize: 10,
      page: 1,
      uploadHeaders: {
        Authorization: `Bearer ${user.token}`
      },
      selected: null // 选中的图片索引
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadImages(1)
  },
  mounted () {
  },
  methods: {
    loadImages (page = 1) {
      this.page = page
      getImages({
        page,
        perPage: this.pageSize,
        collect: this.is_collected
      }).then(res => {
        const {
          results,
          total_count: totalCount
        } = res.data
        // 往img对象中添加loading变量记录每个图片的loading状态
        results.forEach(img => {
          img.loading = false
        })
        this.images = results
        this.totalCount = totalCount
      })
    },

    // 上传素材成功时触发
    onUploadSuccess () {
      // 关闭上传素材对话框
      this.dialogUploadVisible = false
      // 刷新素材图片列表
      this.loadImages(1)
    },

    // 分页按钮
    onPageChange (page) {
      this.loadImages(page)
    },

    // 收藏或取消收藏
    onCollect (img) {
      // 点击收藏，开启loading状态
      img.loading = true
      collectImages(img.id, !img.is_collected).then(res => {
        img.is_collected = !img.is_collected
        // 收藏成功，关闭loading状态
        img.loading = false
      })
    },

    // 删除图片素材
    onDelete (img) {
      // 收藏和删除共用同一个loading状态，
      // 即收藏时不能删除，删除时不能收藏
      img.loading = true
      this.$confirm('确定删除吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteImages(img.id).then(res => {
          img.loading = false
          this.$message({
            type: 'success',
            message: '素材删除成功'
          })
          this.loadImages(this.page)
        })
      }).catch(() => {
        img.loading = false
      })
    }
  }
}
</script>

<style scoped lang="less">
.action-head {
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.image-item {
  position: relative;
}

.image-action {
  font-size: 20px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  height: 40px;
  background-color: rgba(204, 204, 204, .5);
  position: absolute;
  bottom: 4px;
  left: 5px;
  right: 5px;
}

.selected {
  background: url(./selected.png) no-repeat;
  background-size: cover;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
